package com.anuo.app.common.globalhandle.Interceptor;

import java.util.Calendar;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.anuo.app.common.entity.Response;
import com.anuo.app.common.globalhandle.AppException;
import com.anuo.app.common.globalhandle.GlobalConfig;
import com.anuo.app.common.utils.DateUtil;
import com.anuo.app.common.utils.JsonUtil;
import com.anuo.app.modules.system.entity.Maintenance;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 显示正在维护 拦截器
 * 思路: 此拦截器依赖内存中的inMaintenance 标识, inMaintenance 默认是false 即不会拦截请求, 当调用 apiSetMaintenance
 *  接口将 inMaintenance 设置为true时, 就返回消息说服务器维护中 , 集群时需要将每个机子的apiSetMaintenance接口调用哈
 *  这样用户不管杂个访问都是维护中
 * 参考:
 * http://www.baeldung.com/spring-mvc-handlerinterceptor
 * https://www.mkyong.com/spring-mvc/spring-mvc-handler-interceptors-example/
 */
public class MaintenanceInterceptor extends HandlerInterceptorAdapter {

    //before the actual handler will be executed
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler)
            throws Exception {
        //不拦截维护接口
        if (request.getRequestURL().toString().contains("apiSetMaintenance"))
            return true;
        //维护中处理
        if (GlobalConfig.inMaintenance) {
            //构建响应消息
            Response responseMy = new Response();
            responseMy.setMessage("服务器维护中,暂时不能访问.时间:"
                    + DateUtil.dateToStr(GlobalConfig.maintenanceBeginTime) + " 至 "
                    + DateUtil.dateToStr(GlobalConfig.maintenanceEndTime)
            );
            responseMy.setSuccess(false);
            String msg = JsonUtil.toJson(responseMy);

            //返回响应消息
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Content-Type","application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(msg);
            response.getWriter().flush();

            return false;
        }

        return true;
    }
}